package com.taotao.search.controller;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.bean.TaotaoResult;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.SearchService;

@Controller
@ResponseBody
public class SearchController {
	
	@Autowired
	private SearchService searchService;

	/**
	 * 接受查询参数、页码、每页行数 调用service接口查询 将查询结果包装到TaotaoResult中返回一个json
	 * 
	 * 
	 */
	@RequestMapping(value="/query",method=RequestMethod.GET)
	public TaotaoResult search(@RequestParam("q") String queryString, 
			@RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "60") Integer rows) {
		// 检查查询条件
		if (StringUtils.isBlank(queryString)) {
			return TaotaoResult.build(400, "您还没有输入查询条件！");
		}
		SearchResult searchResult = null;
		try {
			// 解决乱码
			queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
			// 执行查询
			searchResult = searchService.search(queryString, page, rows);
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(400, ExceptionUtils.getStackTrace(e));
		}
		return TaotaoResult.ok(searchResult);

	}

}
